package com.fenghongzhang.lib_okhttp_retrofit_rxjava

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.launch
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.GET
import java.io.IOException
import java.util.concurrent.TimeUnit


class ThreeMainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.three_activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }


        val client = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build()


        val retrofit = Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create()) //添加Gson转换器
            .build()

        lifecycleScope.launch {
            val user = retrofit.create(ApiService2::class.java).getUser() //协程进行线程切换,异步

        }


    }

    private fun java的用法() {
        //创建ohhttp客户端
        val client = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build()

        val retrofit = Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create()) //添加Gson转换器
            .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) //添加RxJava转换器 把CallBack
            .build()

        retrofit.create(ApiService::class.java).getUser()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                println(it) //User对象
            }
    }

    private fun okhttp() {
        val client = OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build()

        val request = Request.Builder()
//            .post(RequestBody.create("application/json".toMediaTypeOrNull(), "{\"name\":\"square\"}"))
            .get()
            .url("https://api.github.com/users/square/1")
            .build()


        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                e.printStackTrace()
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (response.isSuccessful) {
                        println(response.body?.string()) //字符串"{code:2,message:"haohao"}"
                    } else {
                        println("Request failed: ${response.code}")
                    }
                }
            }
        })
    }

    private fun rxjava() {
        val observable = Observable.just("Hello", "World")
        observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .map { s: String -> s.toUpperCase() }
            .filter { s: String? -> s!!.length > 0 }
            .subscribe(Consumer { s: String? ->
                println(s)
            })
    }
}

interface ApiService {
    @GET("users/square/1")
    fun getUser(): Observable<User>
}

interface ApiService2 {
    @GET("users/square/1")
    suspend fun getUser(): User
}